import React, { Component } from 'react'
// 创建context对象
const MyContext = React.createContext()
const {Provider,Consumer} = MyContext
export default class A extends Component {
    state = {
        userName: 'fong',
        age: 18
    }
  render() {
    const {userName, age} = this.state
    return (
        <div>
            <h1>我是A组件</h1>
            <h1>我的用户名是:{userName}</h1>
            <Provider value={{userName, age}}>
            <B/>
            </Provider>
        </div>
    )
  }
}
class B extends Component {
    render() {
        return (
            <div>
            <h1>我是B组件</h1>
            <C/>
        </div>
        )
    }
}
class C extends Component {
    // 声明接收context
    static contextType = MyContext
    render() {
    let {userName, age} = this.context
    return (
            <div>
            <h1>我是C组件</h1>
            <h1>我的用户名是:{userName}， 我的年龄是：{age}</h1>
            <D/>
        </div>
        )
    }
}
// 函数式组件的用法：通过Consumer访问祖先组件的传值
function D(){
    return (
        <div>
            <h1>我是D组件</h1>
            <Consumer>
            {
                value=>{
                    return (
                        <h1>我的用户名是:{value.userName}, 我的年龄是:{value.age}</h1>
                    )
                }
            }
            </Consumer>
            {/* <h4>我从A组件接收到的数据：</h4>
            <Consumer>
            {
                value=>{
                    return `用户名：${value.userName}, 年龄：${value.age}`
                }
            }
            </Consumer> */}
        </div>
    )
}